package com.gxnu.edu.cn.ttxxt.service.Impl;

import com.gxnu.edu.cn.ttxxt.entity.ChatGroups;
import com.gxnu.edu.cn.ttxxt.entity.GroupsMembers;
import com.gxnu.edu.cn.ttxxt.entity.Notifications;
import com.gxnu.edu.cn.ttxxt.mapper.ChatGroupRepository;
import com.gxnu.edu.cn.ttxxt.mapper.GroupMemberRepository;
import com.gxnu.edu.cn.ttxxt.mapper.NotificationRepository;
import com.gxnu.edu.cn.ttxxt.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class GroupServiceImpl implements GroupService {

    @Autowired
    private ChatGroupRepository chatGroupMapper;

    @Autowired
    private GroupMemberRepository groupMemberMapper;

    @Autowired
    private NotificationRepository notificationMapper;

    @Override
    @Transactional
    public ChatGroups createGroup(Long creatorId, String groupName, String description) {
        // 参数校验
        if (creatorId == null || groupName == null || groupName.trim().isEmpty()) {
            throw new IllegalArgumentException("创建群组参数不完整");
        }

        // 创建新群组
        ChatGroups group = new ChatGroups();
        group.setGroupName(groupName);
        group.setDescription(description);
        group.setCreatorId(creatorId);
        group.setCreateTime(new Date());
        group.setUpdateTime(new Date());
        chatGroupMapper.save(group);
        // 将创建者添加为群主
        GroupsMembers member = new GroupsMembers();
        member.setGroupId(group.getGroupId());
        member.setUserId(creatorId);
        member.setRole(3); // 默认普通成员
        member.setJoinTime(new Date());
        groupMemberMapper.add(member); // 3代表群主角色

        return group;
    }

    @Override
    @Transactional
    public void addMember(Long groupId, Long userId, Integer role) {
        // 参数校验
        if (groupId == null || userId == null) {
            throw new IllegalArgumentException("群组ID和用户ID不能为空");
        }

        // 检查群组是否存在
        if (!chatGroupMapper.selectBygroupIdd(groupId)) {
            throw new IllegalArgumentException("群组不存在");
        }

        // 检查用户是否已在群组中
        if (groupMemberMapper.existsByUserIdAndGroupId(userId, groupId)) {
            throw new IllegalArgumentException("用户已在群组中");
        }

        // 添加群成员
        addGroupMember(groupId, userId, role);
    }

    private void addGroupMember(Long groupId, Long userId, Integer role) {
        GroupsMembers member = new GroupsMembers();
        member.setGroupId(groupId);
        member.setUserId(userId);
        member.setRole(role != null ? role : 1); // 默认普通成员
        member.setJoinTime(new Date());
        groupMemberMapper.add(member);
    }

    @Override
    @Transactional
    public void removeMember(Long groupId, Long userId) {
        // 参数校验
        if (groupId == null || userId == null) {
            throw new IllegalArgumentException("群组ID和用户ID不能为空");
        }

        // 检查是否是群主
        GroupsMembers operator = groupMemberMapper.selectByGroupIdAndUserId(groupId, userId);
        if (operator != null && operator.getRole() == 3) {
            throw new IllegalArgumentException("不能移除群主，请先转让群主权限");
        }

        int affected = groupMemberMapper.deleteByGroupIdAndUserId(groupId, userId);
        if (affected == 0) {
            throw new IllegalArgumentException("群成员不存在");
        }
    }

    @Override
    @Transactional
    public void updateMemberRole(Long groupId, Long userId, Integer role) {
        // 参数校验
        if (groupId == null || userId == null || role == null) {
            throw new IllegalArgumentException("参数不能为空");
        }

        // 检查角色值是否合法
        if (role < 1 || role > 3) {
            throw new IllegalArgumentException("无效的角色值");
        }

        GroupsMembers member = groupMemberMapper.selectByGroupIdAndUserId(groupId, userId);
        if (member == null) {
            throw new IllegalArgumentException("群成员不存在");
        }

        // 检查是否尝试修改群主角色
        if (member.getRole() == 3 && role != 3) {
            throw new IllegalArgumentException("不能直接修改群主角色，请先转让群主权限");
        }

        member.setRole(role);
        int affected = groupMemberMapper.update(member);
        if (affected == 0) {
            throw new RuntimeException("更新群成员角色失败");
        }
    }

    @Transactional
    @Override
    public void transferOwnership(Long groupId, Long currentOwnerId, Long newOwnerId) {
        // 参数校验
        if (groupId == null || currentOwnerId == null || newOwnerId == null) {
            throw new IllegalArgumentException("参数不能为空");
        }

        // 验证当前操作者是否是群主
        GroupsMembers currentOwner = groupMemberMapper.selectByGroupIdAndUserId(groupId, currentOwnerId);
        if (currentOwner == null || currentOwner.getRole() != 3) {
            throw new IllegalArgumentException("只有群主可以转让群主权限");
        }

        // 获取新群主成员记录
        GroupsMembers newOwner = groupMemberMapper.selectByGroupIdAndUserId(groupId, newOwnerId);
        if (newOwner == null) {
            throw new IllegalArgumentException("新群主不是当前群成员");
        }

        // 更新角色
        currentOwner.setRole(1); // 原群主变为普通成员
        newOwner.setRole(3);     // 新成员成为群主

        groupMemberMapper.update(currentOwner);
        groupMemberMapper.update(newOwner);
    }

    @Override
    @Transactional
    public void dissolveGroup(Long groupId, Long operatorId) {
        // 参数校验
        if (groupId == null || operatorId == null) {
            throw new IllegalArgumentException("参数不能为空");
        }

        // 验证操作者是否为群主
        GroupsMembers operator = groupMemberMapper.selectByGroupIdAndUserId(groupId, operatorId);
        if (operator == null || operator.getRole() != 3) {
            throw new IllegalArgumentException("只有群主可以解散群组");
        }

        // 先删除所有群成员
        groupMemberMapper.deleteByGroupId(groupId);

        // 然后删除群组
        chatGroupMapper.delete(groupId);
    }

    @Override
    public List<ChatGroups> getUserGroups(Long userId) {
        // 参数校验
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        return chatGroupMapper.selectByUserId(userId);
    }

    @Override
    public List<GroupsMembers> getGroupMembers(Long groupId) {
        // 参数校验
        if (groupId == null) {
            throw new IllegalArgumentException("群组ID不能为空");
        }

        return groupMemberMapper.findByGroupId(groupId);
    }

    @Override
    public List<GroupsMembers> getGroupAdmins(Long groupId) {
        // 参数校验
        if (groupId == null) {
            throw new IllegalArgumentException("群组ID不能为空");
        }

        return groupMemberMapper.findByGroupIdAndRole(groupId, 2); // 2表示管理员
    }

    @Override
    public ChatGroups getGroupInfo(Long groupId) {
        // 参数校验
        if (groupId == null) {
            throw new IllegalArgumentException("群组ID不能为空");
        }

        ChatGroups group = chatGroupMapper.selectById(groupId);
        if (group == null) {
            throw new IllegalArgumentException("群组不存在");
        }
        return group;
    }

    @Override
    public ChatGroups dissolveGroupName(String groupName, Long operatorId) {
        // 参数校验
        if (groupName == null) {
            throw new IllegalArgumentException("群组名不能为空");
        }

        ChatGroups group = chatGroupMapper.selectByGroupName(groupName);
        if (group == null) {
            throw new IllegalArgumentException("群组不存在");
        }
        return group;
    }

    @Override
    public List<ChatGroups> getUserJoinGroups(Long userId) {
        List<GroupsMembers> byUserIds = groupMemberMapper.findByUserId(userId);
        List<ChatGroups> chatGroups = new ArrayList<>();
        for(GroupsMembers byUserId :byUserIds){
            ChatGroups chatGroup =chatGroupMapper.searchByGroupId(byUserId.getGroupId());
            chatGroups.add(chatGroup);
        }
        return chatGroups;
    }

    @Override
    public void applyToJoinGroup(Long userId, Long groupId, String message) {
        // 检查是否已是好友
        Boolean isJoined = chatGroupMapper.existsByUserIdAndGroupId(userId, groupId);
        if (isJoined != null && isJoined) {
            throw new IllegalArgumentException("你已经在群组里啦");
        }
        ChatGroups chatGroups = chatGroupMapper.searchByGroupId(groupId);
        // 检查是否已发送过请求
        if (notificationMapper.existsBySenderIdAndReceiverIdAndType(userId, chatGroups.getCreatorId(), 5)) {
            throw new IllegalArgumentException("已发送过好友请求，请等待对方处理");
        }

        // 创建通知
        Notifications notifications = new Notifications();
        notifications.setReceiverId(chatGroups.getCreatorId());
        notifications.setSenderId(userId);
        notifications.setType(5); // 加群请求
        notifications.setContent(message != null ? message : "我想加入群组");
        notifications.setStatus(1); // 未处理
        notifications.setCreateTime(new Date());
        System.out.println(notifications.toString());
        notificationMapper.insert(notifications);
    }
}